package com.sls.web.manager.action.game;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;

import com.sls.web.manager.action.SuperAction;
import com.sls.web.manager.common.Constants;
import com.sls.web.manager.execption.ManagerException;
import com.sls.web.manager.game.pojo.YunEnProduct;
import com.sls.web.manager.game.pojo.YunEnRespInfo;
import com.sls.web.manager.game.service.YunService;
import com.sls.web.manager.page.Pagination;

@InterceptorRefs({
		@InterceptorRef(value = "defaultStack", params = { "maximumSize",
				"2048000", "allowedTypes",
				"text/plain,application/excel,application/vnd.ms-excel" }),
		@InterceptorRef(value = "defalutStackSet") })
public class YunAction extends SuperAction {

	private static final long serialVersionUID = 4095554890062214990L;
	@Resource
	private YunService yunService;

	private YunEnProduct yunProduct;
	private YunEnProduct yunQuery;
	private Pagination<?> page;
	private String id;
	private String productId;
	private String productName;
	private String supplierId;
	private int priceRatio;
	
	private YunEnRespInfo respInfo;
	private String orderId;
	private String merchantId;
	

	private File productExcel;// 获取上传文件
	private String productExcelFileName;// 获取上传文件名称
	private String productExcelContentType;// 获取上传文件类型

	public String add() {
		return INPUT;
	}

	public String save() {
		try {
			this.yunService.save(yunProduct, getCurrentOperator());
			this.redirectionUrl = "yun!list.htm";
		} catch (ManagerException e) {
			flag = false;
			this.addActionError(e.getMessage());
		}
		return SUCCESS;
	}

	/**
	 * 列表展示
	 * 
	 * @return
	 */
	public String list() {
		if (yunQuery == null) {
			yunQuery = new YunEnProduct();
			yunQuery.setCurrentPage(Constants.INIT_CURRENTPAGE);
			yunQuery.setPageSize(Constants.INIT_PAGESIZE);
		}
		try {
			page = this.yunService.queryPage(yunQuery, getCurrentOperator());
		} catch (ManagerException e) {
			this.addActionError(e.getMessage());
		}
		return "list";
	}

	public String toEdit() {
		try {
			yunProduct = this.yunService.queryById(id, getCurrentOperator());
		} catch (ManagerException e) {
			this.addActionError(e.getMessage());
		}
		return INPUT;
	}

	public String edit() {
		try {
			this.yunService.update(yunProduct, getCurrentOperator());
			if (yunQuery == null) {
				yunQuery = new YunEnProduct();
				yunQuery.setCurrentPage(Constants.INIT_CURRENTPAGE);
				yunQuery.setPageSize(Constants.INIT_PAGESIZE);
			}
			if (StringUtils.isNotEmpty(productId)) {
				yunQuery.setProductId(productId);
			}
			if (StringUtils.isNotEmpty(productName)) {
				yunQuery.setProductName(productName);
			}
		} catch (ManagerException e) {
			this.addActionError(e.getMessage());
		}
		return list();
	}

	public String audit() {

		try {
			this.yunService.confirmAudit(supplierId, priceRatio,
					getCurrentOperator());
			redirectionUrl = "yun!list.htm";
		} catch (ManagerException e) {
			flag = false;
			addActionError(e.getMessage());
		}
		return SUCCESS;

	}
	
	public String toQueryOrder() {
		return "order";
	}

	public String queryOrder() {
		try {
			respInfo = this.yunService.queryOrder(orderId,
					getCurrentOperator());
			respInfo.setMerchantId(merchantId);
		} catch (ManagerException e) {
			this.addActionError(e.getMessage());
		}
		return "order";
	}

	/**
	 * 批量上架
	 * 
	 * @return
	 * @throws Exception
	 */
	public String batchOnline() throws Exception {
		try {
			this.yunService.batchOnline("1", getCurrentOperator());
			redirectionUrl = "yun!list.htm";
		} catch (ManagerException e) {
			flag = false;
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}

	/**
	 * 批量下架
	 * 
	 * @return
	 * @throws Exception
	 */
	public String batchOffline() throws Exception {
		try {
			this.yunService.batchOffline("0", getCurrentOperator());
			redirectionUrl = "yun!list.htm";
		} catch (ManagerException e) {
			flag = false;
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}

	/**
	 * 导入产品excel文件
	 * 
	 * @return
	 * @throws Exception
	 */
	public String importProductFile() throws Exception {
		if (StringUtils.isEmpty(productExcelFileName)) {
			flag = false;
			addActionError("请选择要导入的文件!");
			return SUCCESS;
		}
		if (!productExcelFileName.endsWith(".xls")
				&& !productExcelFileName.endsWith(".xlsx")) {
			flag = false;
			addActionError("文件类型有误!<br>必须为excel文件!");
			return SUCCESS;
		}
		InputStream is = null;
		try {
			is = new FileInputStream(productExcel);
		} catch (FileNotFoundException e1) {
			addActionError(e1.getMessage());
		}
		List<YunEnProduct> list = null;
		try {
			if (is != null) {
				if (productExcelFileName.endsWith(".xls")) {
					list = this.extractListFromXLS2003(is);
				} else if (productExcelFileName.endsWith(".xlsx")) {
					list = this.extractListFromXLS2007(is);
				}
			}
		} catch (IOException e) {
			addActionError(e.getMessage());
		}
		String message = "";
		if (list != null && !list.isEmpty()) {
			for (YunEnProduct yun : list) {
				if (yun != null && StringUtils.isNotEmpty(yun.getProductId())) {
					try {
						yun.setRechargeMode("2");
						this.yunService.save(yun, getCurrentOperator());
					} catch (ManagerException e) {
						message += yun.getProductId() + "," + e.getMessage()
								+ "<br>";
						continue;
					}
				}
			}
		}
		if (StringUtils.isNotEmpty(message)) {
			flag = false;
			addActionError(message);
		}
		this.redirectionUrl = "yun!list.htm";
		return SUCCESS;
	}

	/**
	 * 解析excel2003文件
	 * 
	 * @param is
	 * @return
	 * @throws IOException
	 */
	private List<YunEnProduct> extractListFromXLS2003(InputStream is)
			throws IOException {
		List<YunEnProduct> list = new ArrayList<YunEnProduct>();
		YunEnProduct yun = null;
		HSSFWorkbook workbook = new HSSFWorkbook(is); // 创建对Excel工作簿文件的引用
		for (int numSheets = 0; numSheets < workbook.getNumberOfSheets(); numSheets++) {
			if (null != workbook.getSheetAt(numSheets)) {
				HSSFSheet aSheet = workbook.getSheetAt(numSheets); // 获得一个sheet
				for (int rowNumOfSheet = 1; rowNumOfSheet <= aSheet
						.getLastRowNum(); rowNumOfSheet++) {
					if (null != aSheet.getRow(rowNumOfSheet)) {
						yun = new YunEnProduct();
						List<String> cellList = new ArrayList<String>();
						HSSFRow aRow = aSheet.getRow(rowNumOfSheet); // 获得一行
						for (int cellNumOfRow = 0; cellNumOfRow <= aRow
								.getLastCellNum(); cellNumOfRow++) {
							if (null != aRow.getCell(cellNumOfRow)) {
								HSSFCell aCell = aRow.getCell(cellNumOfRow); // 获得列值
								if (aCell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
									double parvalue = aCell
											.getNumericCellValue();
									cellList.add(String.valueOf(parvalue));
								} else if (aCell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
									boolean flag = aCell.getBooleanCellValue();
									cellList.add(String.valueOf(flag));
								} else {
									cellList.add(aCell.getStringCellValue());
								}

								if (cellList.size() > 0) {
									yun.setProductId(cellList.get(0));
								}
								if (cellList.size() > 1) {
									yun.setProductName(cellList.get(1));
								}
								if (cellList.size() > 2) {
									yun.setProductParvalue(cellList.get(2));
								}
								if (cellList.size() > 3) {
									yun.setProductPrice(cellList.get(3));
								}
							}
						}

					}
					list.add(yun);
				}
			}
		}
		return list;
	}

	/**
	 * 解析excel2007文件
	 * 
	 * @param is
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	private List<YunEnProduct> extractListFromXLS2007(InputStream is)
			throws IOException {
		List<YunEnProduct> list = new ArrayList<YunEnProduct>();
		YunEnProduct yun = null;
		// 构造 XSSFWorkbook 对象，strPath
		// 传入文件路径
		XSSFWorkbook xwb = new XSSFWorkbook(is);
		// 循环工作表Sheet
		for (int numSheet = 0; numSheet < xwb.getNumberOfSheets(); numSheet++) {
			XSSFSheet xSheet = xwb.getSheetAt(numSheet);
			if (xSheet == null) {
				continue;
			}
			// 循环行Row
			for (int rowNum = 1; rowNum <= xSheet.getLastRowNum(); rowNum++) {
				yun = new YunEnProduct();
				XSSFRow xRow = xSheet.getRow(rowNum);
				if (xRow == null) {
					continue;
				}
				List<String> cellList = new ArrayList<String>();
				// 循环列Cell
				for (int cellNum = 0; cellNum <= xRow.getLastCellNum(); cellNum++) {
					XSSFCell xCell = xRow.getCell(cellNum);

					if (xCell == null) {
						continue;
					}
					if (xCell.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN) {
						boolean flag = xCell.getBooleanCellValue();
						cellList.add(String.valueOf(flag));
					} else if (xCell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
						double parvalue = xCell.getNumericCellValue();
						cellList.add(String.valueOf(parvalue));
					} else {
						cellList.add(xCell.getStringCellValue());
					}
					if (cellList.size() > 0) {
						yun.setProductId(cellList.get(0));
					}
					if (cellList.size() > 1) {
						yun.setProductName(cellList.get(1));
					}
					if (cellList.size() > 2) {
						yun.setProductParvalue(cellList.get(2));
					}
					if (cellList.size() > 3) {
						yun.setProductPrice(cellList.get(3));
					}
				}
				list.add(yun);
			}
		}
		return list;
	}

	public YunEnProduct getYunProduct() {
		return yunProduct;
	}

	public void setYunProduct(YunEnProduct yunProduct) {
		this.yunProduct = yunProduct;
	}

	public YunEnProduct getYunQuery() {
		return yunQuery;
	}

	public void setYunQuery(YunEnProduct yunQuery) {
		this.yunQuery = yunQuery;
	}

	public Pagination<?> getPage() {
		return page;
	}

	public void setPage(Pagination<?> page) {
		this.page = page;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getProductId() {
		return productId;
	}

	public void setProductId(String productId) {
		this.productId = productId;
	}

	public File getProductExcel() {
		return productExcel;
	}

	public void setProductExcel(File productExcel) {
		this.productExcel = productExcel;
	}

	public String getProductExcelFileName() {
		return productExcelFileName;
	}

	public void setProductExcelFileName(String productExcelFileName) {
		this.productExcelFileName = productExcelFileName;
	}

	public String getProductExcelContentType() {
		return productExcelContentType;
	}

	public void setProductExcelContentType(String productExcelContentType) {
		this.productExcelContentType = productExcelContentType;
	}

	public String getProductName() {
		return productName;
	}

	public void setProductName(String productName) {
		this.productName = productName;
	}

	public String getSupplierId() {
		return supplierId;
	}

	public void setSupplierId(String supplierId) {
		this.supplierId = supplierId;
	}

	public int getPriceRatio() {
		return priceRatio;
	}

	public void setPriceRatio(int priceRatio) {
		this.priceRatio = priceRatio;
	}

	public YunEnRespInfo getRespInfo() {
		return respInfo;
	}

	public void setRespInfo(YunEnRespInfo respInfo) {
		this.respInfo = respInfo;
	}

	public String getOrderId() {
		return orderId;
	}

	public void setOrderId(String orderId) {
		this.orderId = orderId;
	}

	public String getMerchantId() {
		return merchantId;
	}

	public void setMerchantId(String merchantId) {
		this.merchantId = merchantId;
	}

}
